#include <stdlib.h>
#include <string.h>
#include "valid_domain.h"

#define DOMAIN_MAXLEN 255

#ifndef IS_ALPHA
#define IS_ALPHA(x)   (((x >= 'A') && (x <= 'Z')) || ((x >= 'a') && (x <= 'z')))
#endif

#ifndef IS_DIGIT
#define IS_DIGIT(x)   ((x >= '0') && (x <= '9'))
#endif

int valid_domain (const unsigned char *domain)
{
	const unsigned char *ptr;
	int state;
	size_t len;

	ptr = domain;

	/* Domain = (sub-domain 1*("." sub-domain)) */
	if ((!IS_ALPHA (*ptr)) && (!IS_DIGIT (*ptr))) {
		return -1;
	}

	ptr++;
	len = 1;

	state = 0;

	do {
		if (state == 0) {
			if ((*ptr == '-') || (*ptr == '.')) {
				state = 1;
			} else if ((!IS_ALPHA (*ptr)) && (!IS_DIGIT (*ptr))) {
				break;
			}
		} else {
			if ((!IS_ALPHA (*ptr)) && (!IS_DIGIT (*ptr))) {
				return -1;
			}

			state = 0;
		}

		if (++len > DOMAIN_MAXLEN) {
			return -1;
		}

		ptr++;
	} while (1);

	if (*ptr) {
		return -1;
	}

	return 0;
}
